package com.example.lets;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;

import com.github.ksoichiro.android.observablescrollview.ObservableListView;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ScrollUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.listener.FindListener;

public class ActivitySearchFragment extends BaseFragment {

    public static final String ARG_INITIAL_POSITION = "ARG_INITIAL_POSITION";
    public static Context context = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_listview, container, false);

        Activity parentActivity = getActivity();
        final ObservableListView listView = (ObservableListView) view.findViewById(R.id.scroll);
        listView.addHeaderView(inflater.inflate(R.layout.padding, listView, false));

        final String inputStr = SearchActivity.et.getText().toString();
        String newInputStr = SearchActivity.ruleSearchString(inputStr);

        final ArrayList<UserActivity> retAct = new ArrayList<UserActivity>();
        retAct.clear();

        if (inputStr.equals("")) listView.setAdapter(new MyAdapter(context,  new ArrayList<HashMap<String, Object>>()));
        else {
            BmobQuery<UserActivity> activityQuery = new BmobQuery<UserActivity>("UserActivity");
            BmobQuery<UserActivity> activityNameQuery = new BmobQuery<UserActivity>("UserActivity");
            BmobQuery<UserActivity> activityDescriptionQuery = new BmobQuery<UserActivity>("UserActivity");
            List<BmobQuery<UserActivity>> activityQueries = new ArrayList<BmobQuery<UserActivity>>();
            activityQuery.setLimit(100);
            activityNameQuery.addWhereMatches("name", "(.)*" + newInputStr + "(.)*");
            activityDescriptionQuery.addWhereMatches("description", "(.)*" + newInputStr + "(.)*");
            activityQueries.add(activityNameQuery);
            activityQueries.add(activityDescriptionQuery);
            activityQuery.or(activityQueries);
            activityQuery.findObjects(context, new FindListener<UserActivity>() {
                @Override
                public void onSuccess(List<UserActivity> userActivityResult) {
                    //Log.i("find", "锟斤拷询锟斤拷锟窖达拷锟节碉拷锟街伙拷锟斤拷");
                    for (UserActivity userActivity : userActivityResult) {
                        // 锟斤拷锟絧layerName锟斤拷锟斤拷息
                        BmobDate a = userActivity.getStartTime(), b = userActivity.getEndTime();
                        //Toast.makeText(SearchActivity.this, "xian shi date:" + a.getDate(), Toast.LENGTH_LONG).show();
                        if (userActivity.getName().equals(inputStr))
                            retAct.add(0, userActivity);
                        else {
                            for (int i = 0; i < retAct.size(); i++) {
                                if (userActivity.getObjectId().equals(retAct.get(i).getObjectId()))
                                    break;
                            }
                            retAct.add(userActivity);
                        }
                    }

                    final ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
                    for (UserActivity activity : retAct) {
                        HashMap<String, Object> map = new HashMap<String, Object>();

                        map.put("ItemSponsor", activity.getSponsorName());
                        map.put("ItemPicFileName", activity.getPicFilename());
                        map.put("ItemText", activity.getDescription());
                        map.put("ItemTitle", activity.getName());
                        map.put("number", activity.getPeopleNumber());
                        map.put("sponsorId", activity.getSponsorId());
                        map.put("place", activity.getPlace());
                        map.put("time", activity.getStartTime().getDate());
                        map.put("type", activity.getType());
                        map.put("id", activity.getObjectId());

                        listItem.add(map);
                    }
                    listView.setAdapter(new MyAdapter(context, listItem));
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                        @Override
                        public void onItemClick(AdapterView<?> parent, View view,
                                                int position, long id) {

                            if (position-- < 1) return;

                            String title = (String) listItem.get(position).get("ItemTitle");
                            String description = (String) listItem.get(position).get("ItemText");
                            String picFileName = (String) listItem.get(position).get("ItemPicFileName");
                            String sponsorId = (String) listItem.get(position).get("sponsorId");
                            String type = (String) listItem.get(position).get("type");
                            String place = (String) listItem.get(position).get("place");
                            String time = (String) listItem.get(position).get("time");
                            String ActiId = (String) listItem.get(position).get("id");

                            Intent intent = new Intent(context, EventActivity.class);
                            intent.putExtra("title", title);
                            intent.putExtra("description", description);
                            intent.putExtra("picFileName", picFileName);
                            intent.putExtra("sponsorId", sponsorId);
                            intent.putExtra("place", place);
                            intent.putExtra("time", time);
                            intent.putExtra("type", type);
                            intent.putExtra("id", ActiId);

                            startActivity(intent);
                        }

                    });
                }

                @Override
                public void onError(int arg0, String arg1) {
                    //Toast.makeText(context, "查询\"" + inputStr + "\"错误代码：" + arg1, Toast.LENGTH_LONG).show();
                }
            });
        }

        if (parentActivity instanceof ObservableScrollViewCallbacks) {
            // Scroll to the specified position after layout
            Bundle args = getArguments();
            if (args != null && args.containsKey(ARG_INITIAL_POSITION)) {
                final int initialPosition = args.getInt(ARG_INITIAL_POSITION, 0);
                ScrollUtils.addOnGlobalLayoutListener(listView, new Runnable() {
                    @Override
                    public void run() {
                        // scrollTo() doesn't work, should use setSelection()
                        listView.setSelection(initialPosition);
                    }
                });
            }

            // TouchInterceptionViewGroup should be a parent view other than ViewPager.
            // This is a workaround for the issue #117:
            // https://github.com/ksoichiro/Android-ObservableScrollView/issues/117
            listView.setTouchInterceptionViewGroup((ViewGroup) parentActivity.findViewById(R.id.root));

            listView.setScrollViewCallbacks((ObservableScrollViewCallbacks) parentActivity);
        }
        return view;
    }
}
